package com.yunhe.authority.service.authority.impl;

import com.yunhe.authority.domain.authority.BackUser;
import com.yunhe.authority.repository.authority.BackUserRepository;
import com.yunhe.authority.repository.authority.impl.BackUserDao;
import com.yunhe.authority.service.authority.BackUserService;
import com.yunhe.common.exception.ArgumentErrorException;
import com.yunhe.common.model.PageParam;
import com.yunhe.common.util.DateTimeUtils;
import com.yunhe.common.util.MD5Util;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * @author zhengbo
 * @date 2021/10/21 15:34
 */
@Service
@Slf4j
public class BackUserServiceImpl implements BackUserService {

    @Autowired
    private BackUserRepository backUserRepository;

    @Autowired
    private BackUserDao backUserDao;

    private static final String SALT_M = "yunhe";
    private static final String SALT_V = "@yqlh";

    @Override
    @Transactional(rollbackFor = Exception.class, transactionManager = "transactionManager")
    public BackUser save(BackUser backUser, String roleIds) throws ArgumentErrorException {

        if (StringUtils.isEmpty(backUser.getPassword())
                || StringUtils.isEmpty(backUser.getPhone())
                || StringUtils.isEmpty(backUser.getTitle())) {
            throw new ArgumentErrorException("手机号、密码、姓名不能为空");
        }
        if (StringUtils.isEmpty(roleIds)) {
            throw new ArgumentErrorException("请选择角色");
        }

        BackUser byPhone = backUserRepository.findByPhone(backUser.getPhone());
        if (byPhone != null) {
            throw new ArgumentErrorException("此手机号已存在");
        }
        //密码加密
        if (backUser.getId() == null) {
            backUser.setPassword(MD5Util.encode(backUser.getPassword(), SALT_M));
        }
        backUser.setName(backUser.getPhone());
        backUser.setCreateTime(DateTimeUtils.format(DateTimeUtils.PATTERN.DATETIME.value(), new Date()));
        backUser.setUpdateTime(DateTimeUtils.format(DateTimeUtils.PATTERN.DATETIME.value(), new Date()));
        BackUser newBackUser = backUserRepository.save(backUser);

        //绑定角色
        String[] roleIdsSplit = roleIds.split(",");
        List<Long> roleIdList = new ArrayList<>();
        for (String id : roleIdsSplit) {
            roleIdList.add(Long.valueOf(id));
        }
        backUserRepository.bindBackRole(newBackUser.getId(), roleIdList);

        return newBackUser;
    }

    @Override
    public BackUser update(BackUser backUser) throws ArgumentErrorException {
        if (StringUtils.isEmpty(backUser.getPassword())
                || StringUtils.isEmpty(backUser.getPhone())
                || StringUtils.isEmpty(backUser.getTitle())) {
            throw new ArgumentErrorException("手机号、密码、姓名不能为空");
        }
        Optional<BackUser> optionalBackUser = backUserRepository.findById(backUser.getId());
        if (!optionalBackUser.isPresent()) {
            throw new ArgumentErrorException("账号不存在");
        }
        if (!optionalBackUser.get().getId().equals(backUser.getId())) {
            throw new ArgumentErrorException("此手机号已存在");
        }
        BackUser existBackUser = optionalBackUser.get();
        backUser.setId(existBackUser.getId());
        backUser.setUpdateTime(DateTimeUtils.format(DateTimeUtils.PATTERN.DATETIME.value(), new Date()));
        BackUser newBackUser = backUserRepository.save(backUser);
        return newBackUser;
    }

    @Override
    @Transactional(rollbackFor = Exception.class, transactionManager = "transactionManager")
    public BackUser updatePassword(Long id, String password) {
        return backUserRepository.updatePassword(id, password);
    }

    @Override
    public BackUser findByNameAndPassword(String name, String password) {
        return backUserRepository.findByNameAndPassword(name, password);
    }

    @Override
    public BackUser findByPhoneAndPassword(String phone, String password) throws ArgumentErrorException {
        password = MD5Util.encode(password, SALT_M);
        BackUser byPhone = backUserRepository.findByPhone(phone);
        if (byPhone == null) {
            throw new ArgumentErrorException("手机号未注册");
        }
        if (!byPhone.getPassword().equals(password)) {
            throw new ArgumentErrorException("密码错误");
        }
        BackUser backUser = backUserRepository.findByPhoneAndPassword(phone, password);
        return backUser;
    }

    @Override
    public BackUser findByName(String name) {
        return backUserRepository.findByName(name);
    }

    @Override
    public BackUser findByPhone(String phone) {
        return backUserRepository.findByPhone(phone);
    }

    @Override
    public BackUser findByUserId(Long userId) {
        return backUserRepository.findById(userId).orElse(new BackUser());
    }

    @Override
    @Transactional(rollbackFor = Exception.class, transactionManager = "transactionManager")
    public void deleteById(Long id) {
        backUserRepository.deleteById(id);
    }

    @Override
    public Page<BackUser> findUsersByIdAndCondition(Long id, String keywords, PageParam pageParam) {
        return backUserDao.findUsersById(id, keywords, pageParam);
    }
}
